<?php 
session_start();
function findsubarray($array=array(),$parentid){
    $rs=array();
    foreach ($array as $a){
        if($parentid==$a["parentid"])
        $rs[]=$a;
    }
    return $rs;
}
function finditem($array=array(),$id){

    foreach ($array as $a){
        if($id==$a["id"])
        return $a;
    }
    return null;
}
class orders extends CI_Controller  {

        /**
        * Index Page for this controller.
        *
        * Maps to the following URL
        * 		http://example.com/index.php/welcome
        *	- or -  
        * 		http://example.com/index.php/welcome/index
        *	- or -
        * Since this controller is set as the default controller in 
        * config/routes.php, it's displayed at http://example.com/
        *
        * So any other public methods not prefixed with an underscore will
        * map to /index.php/welcome/<method_name>
        * @see http://codeigniter.com/user_guide/general/urls.html
        */
       private $_configs = null;
       function __construct()
        {
            parent::__construct();
            $this->load->helper('url');
            $this->load->library('javascript');
            $this->load->library('session');
            $this->load->library('smarty3','','smarty');
            $this->_configs["title"]="Quản Lý Deal";
            $this->_configs["authority"]="deal";
            $this->_configs["MinAuthority"]=0;
            $this->load->model('deal/category_model','category_model'   );
            $this->load->model('deal/product_model' ,'product_model'    );
            $this->load->model('deal/customer_model','customer_model'   );
            $this->load->model('deal/order_model'   ,'order_model'      );
            $this->load->model('deal/guide_model'   ,'guide_model'      );
            $this->load->model('admin-planners/region_model','region_model');
            $_SESSION["DRegion"]=isset($_SESSION["DRegion"])?$_SESSION["DRegion"]:"";
            $_SESSION["DRegionName"]=isset($_SESSION["DRegionName"])?$_SESSION["DRegionName"]:"Toàn Quốc";
            
        }
        public function index()
	{
            
	}
        
        function initsubcity(){
            $parentid=$_GET["parentid"];
            $subcity=objectToArray($this->region_model->getByParent($parentid));
            
            
            
            echo "<select id='cbx-quan' class='cyrle' style='width: 160px;margin-right: 20px' onchange='subcitychange($(this).val());'>";
            echo '<option value="-1">[---Chọn quận---]</option>';
            if(count($subcity)>0)foreach ($subcity as $c){
                    echo '<option value="'.$c["id"].'">'.$c["name"].'</option>';
            }
            echo "</select>";
            echo "<span class='ssubcity'><select id='cbx-phuong' class='cyrle' style='width: 160px'>";

            echo '<option value="-1">[---Chọn phường---]</option>';

            echo "</select></span>";
                
            
            
        }
        function initssubcity(){
            $parentid=$_GET["parentid"];
            $subcity=objectToArray($this->region_model->getByParent($parentid));
            
            echo "<select id='cbx-phuong' class='cyrle' style='width: 160px' onchange='changeshipprice($(this).val());'>";
            echo '<option value="-1">[---Chọn phường---]</option>';
            if(count($subcity)>0)foreach ($subcity as $c){
                    echo '<option value="'.$c["id"].'">'.$c["name"].'</option>';
            }
            echo "</select>";
            
        }
        function shipprice(){
            echo isset($_SESSION["ShipInfo"]["ShipPrice"])?number_format($_SESSION["ShipInfo"]["ShipPrice"], 0, ',', '.')."<sup>đ</sup>":"0<sup>đ</sup>";
        }
        function tongthanhtien(){
            
            $t=(isset($_SESSION["TOTALCASH"])?$_SESSION["TOTALCASH"]:0)+(isset($_SESSION["ShipInfo"]["ShipPrice"])?$_SESSION["ShipInfo"]["ShipPrice"]:0);
            echo number_format($t, 0, ',', '.')."<sup>đ</sup>";
        }
        function changeshipprice($v="-1"){
            $shipprice=$_SESSION["ShipInfo"]["ShipPrice"];
            $parentid=$v;
            $re=$this->region_model->getById($parentid);
            if(isset($re[0]))$shipprice=$re[0]->ship;
            $_SESSION["ShipInfo"]["ShipPrice"]=$shipprice;
            echo number_format($_SESSION["ShipInfo"]["ShipPrice"], 0, ',', '.')."<sup>đ</sup>";
        }
        public function buy($alias="")
	{
            if(!isset($_SESSION["D-USER"])){ LoginError (); }
            //unset($_SESSION["ShipInfo"]);
            $shipprice=0;
            $Configs=null;
            $Configs["menu"]="dealdetail";
            $Configs["U"]["avata"]="default";
            $Configs["U"]["email"]="";
            
            
            //$CFregion= objectToArray(json_decode(@file_get_contents(APPPATH."HTML_DOM/CFregion.txt")));
            
            $OtherInfo=  objectToArray(@json_decode($_SESSION["D-USER"]["Note"]));
            
            
            $region=isset($OtherInfo["AddInfo"]["Region"])?$OtherInfo["AddInfo"]["Region"]:"-1";
            $co=isset($OtherInfo["AddInfo"]["Co"])?$OtherInfo["AddInfo"]["Co"]:"-1";
            $subco=isset($OtherInfo["AddInfo"]["subCo"])?$OtherInfo["AddInfo"]["subCo"]:"-1";
            $Configs["AddInfo"]=$OtherInfo["AddInfo"];
            $Configs["AddInfo"]["Region"]=$region;
            $Configs["AddInfo"]["Co"]=$co;
            $Configs["AddInfo"]["subCo"]=$subco;
            $Configs["AddInfo"]["NumHouse"]=isset($Configs["AddInfo"]["NumHouse"])?$Configs["AddInfo"]["NumHouse"]:"";
            $id=$subco!="-1"?$subco:$co!="-1"?$co:$region!="-1"?$region:"-1";
            if($id!="-1"){
                $re=$this->region_model->getById($id);
                if(isset($re[0]))$shipprice=$re[0]->ship;
            }
            
//            $city=findsubarray($CFregion,"1");
//            $subcity=findsubarray($CFregion,$region);
//            $ssubcity=findsubarray($CFregion,$co);
            $city=  objectToArray($this->region_model->getByParent(0));//findsubarray($CFregion,"1");
            $subcity=isset($OtherInfo["AddInfo"]["Region"])?objectToArray($this->region_model->getByParent($Configs["AddInfo"]["Region"])):array();
            $ssubcity=isset($OtherInfo["AddInfo"]["Co"])?objectToArray($this->region_model->getByParent($Configs["AddInfo"]["Co"])):array();
            
            
            
//            $Configs["AddInfo"]["strRegion"]=  finditem($CFregion,$region);
//            $Configs["AddInfo"]["strCo"]=  finditem($CFregion,$co);
//            $Configs["AddInfo"]["strsubCo"]=  finditem($CFregion,$subco);
            $Configs["AddInfo"]["strRegion"]=  finditem($city,$region);
            $Configs["AddInfo"]["strCo"]=  finditem($subcity,$co);
            $Configs["AddInfo"]["strsubCo"]=  finditem($ssubcity,$subco);
            
            $data["city"]=$city;
            $data["subcity"]=$subcity;
            $data["ssubcity"]=$ssubcity;
            $Configs["alias"]=$alias;
            if(isset($_SESSION["D-USER"])){
                $Configs["U"]=$_SESSION["D-USER"];
                if(!isset($_SESSION["ShipInfo"]))
                    $_SESSION["ShipInfo"]=array("ShipName"=>$_SESSION["D-USER"]["CustomerName"],"ShipPhone"=>$_SESSION["D-USER"]["Phone"],"ShipMail"=>$_SESSION["D-USER"]["Mail"],"ShipNote"=>"");
            }else{
                
            }
            
            
            
            $_SESSION["ShipInfo"]["ShipPrice"]=$shipprice;
            $data["product"]   =   objectToArray($this->product_model->getByAlias($alias));
            
            if(count($data["product"])==0){
                 show_404();
                 return;
            }
            $Configs["Foot"]=@file_get_contents(APPPATH."HTML_DOM/Foot.txt");
            $data["product"]=$data["product"][0];
            $_SESSION["BUY-PROD"]=$data["product"];
            $_SESSION["TOTALCASH"]=$_SESSION["BUY-PROD"]["UnitsOnOrder"];
            
            $_SESSION['ShipInfo']["ShipPhone"]=isset($_SESSION['ShipInfo']["ShipPhone"])?$_SESSION['ShipInfo']["ShipPhone"]:$_SESSION["D-USER"]["Phone"];
            $data["otherproduct"]=objectToArray($this->product_model->getOtherByTag($data["product"]["ProductID"],$data["product"]["Tag"]));
            
            $data["product"]["Discount"]=round(($data["product"]["UnitPrice"]-$data["product"]["UnitsOnOrder"])*100/$data["product"]["UnitPrice"],0);
            
            $data["regions"]=  objectToArray($this->region_model->getByParent("0"));
            
            $data["note1"]=$this->guide_model->getByID("42");
            $data["note2"]=$this->guide_model->getByID("43");
            
            $this->smarty->assign('data', $data);
            $this->smarty->assign('Configs', $Configs);
            $this->smarty->assign('_SESSION', $_SESSION);
            $this->smarty->view     (   "deal/subs/00_css"       ,"dcss"         );
            $this->smarty->view     (   "deal/subs/00_script"    ,"dscript"      );
            $this->smarty->view     (   "deal/subs/01_head"      ,"dhead"        );
            $this->smarty->view     (   "deal/subs/02_menu"      ,"dmenu"        );
            $this->smarty->view     (   "deal/subs/03_foot"      ,"dfoot"        );
            $this->smarty->view     (   "deal/pages/13_buy"   ,"dpage"        ); 
            $this->smarty->display  (   "deal/01_home"                           );
	}
        public function step1(){
            if(!isset($_SESSION["D-USER"])){
                $code=-1;
                $msg="Bạn chưa đăng nhập. Để mua hàng bạn cần phải có tài khoản. Có thể đăng ký hoặc sử dụng OpenID.";
            }else{
                
                $code=1;
                $msg=  "
                    <fieldset style='margin-top:12px'><legend><b>Thông tin người nhận</b></legend>
                    <table style=\"width: 100%;margin-top:8px\" class='dt'>
                        <tr>
                            <td>Người Nhận</td>
                            <td colspan=3>".$_POST["params"]["ShipName"]."</td>
                        </tr>
                        <tr>
                            <td>Số điện thoại</td>
                            <td>".$_POST["params"]["ShipPhone"]."</td>
                            <td></td>
                            <td></td>
                        </tr>
                        <tr>
                            <td>Nội Dung</td>
                            <td colspan=3><pre style='white-space: pre-wrap;       /* css-3 */
 white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
 white-space: -pre-wrap;      /* Opera 4-6 */
 white-space: -o-pre-wrap;    /* Opera 7 */
 word-wrap: break-word; '>".$_POST["params"]["ShipNote"]."</pre></td>
                        </tr>
                    </table>
                    </fieldset>
                    ";
            }
            $rs=array("code"=>$code,"msg"=>$msg);
            echo json_encode($rs);
        }
        public function step2(){
            $CFregion= objectToArray($this->region_model->gets());
            if(!isset($_SESSION["D-USER"])){
                $code=-1;
                $msg="Bạn chưa đăng nhập. Để mua hàng bạn cần phải có tài khoản. Có thể đăng ký hoặc sử dụng OpenID.";
            }else{
                
                $code=1;
                $msg=  "
                    <fieldset style='margin-top:12px'><legend>Thông tin thanh toán - nhận hàng</legend>
                    <table style=\"width: 100%;margin-top:8px\" class='dt'>
                        <tr>
                            <td>Hình thức thanh toán</td>
                            <td colspan=3>".$_POST["params"]["PayType"]."</td>
                        </tr>
                        ";
                if($_POST["params"]["PayType"]=="Thanh toán trực tiếp tại công ty"){
                    $msg.="
                        <tr>
                            <td colspan=4>Bạn vui lòng đến địa chỉ abcxyz để thanh toán và nhận hàng.</td>
                        </tr>";
                }else{
                    
                    $re=finditem($CFregion,$_POST["params"]["Region"]);
                    $co=finditem($CFregion,$_POST["params"]["Co"]);
                    $subco=finditem($CFregion,$_POST["params"]["subCo"]);
                    $msg.="
                         <tr>
                            <td>Địa chỉ giao hàng</td>
                            <td colspan=3>".$_POST["params"]["strShipAddress"]."</td>
                        </tr>
                        ";
                
                }
                $msg.="
                    </table>
                    </fieldset>
                    ";
            }
            $rs=array("code"=>$code,"msg"=>$msg);
            echo json_encode($rs);
        }
        public function OrderFinish(){
            if(!isset($_SESSION["D-USER"])){
                $code=-1;
                $msg="Không xác định được thông tin người mua.";
            }elseif(!is_numeric($_POST["Amount"])){
                $code=-1;
                $msg="Số lượng sản phẩm không hợp lệ";
            }else{
                $product   =   objectToArray($this->product_model->get($_POST["ProductID"]));
                if(!isset($product[0])){
                    $code=-1;
                    $msg="Sản Phẩm không tồn tại hoặc đã ngừng bán";
                }else{
                    $product=$product[0];
                    if($product["Amount"]<=$product["Sold"]){
                        $code=-1;
                        $msg="Sản Phẩm tạm thời hết hàng";
                    }else{
                        $shipinfo=$_POST["ShipInfo"];
                        
                        $payinfo=$_POST["PayInfo"];
                        $re=$payinfo["Region"];
                        $co=$payinfo["Co"];
                        $subco=$payinfo["subCo"];
                        
                        
                        
                        $isubco=$this->region_model->getById($subco);
                        $shipprice=0;
                        
                        if(isset($isubco[0]))$shipprice=$isubco[0]->ship;
                        else{
                            $ico=$this->region_model->getById($co);
                            if(isset($ico[0]))$shipprice=$ico[0]->ship;
                            else{
                                $ire=$this->region_model->getById($co);
                                if(isset($ico[0]))$shipprice=$ico[0]->ship;
                                else{
                                    $ire=$this->region_model->getById($re);
                                    if(isset($ire[0]))$shipprice=$ire[0]->ship;
                                }
                            }
                        }
                        $shipprice=0;
                        $shipinfo["ShipCash"]=$shipprice;
                        $Order["Product"]=array(
                            "ProductID"=>$product["ProductID"],
                            "ProductName"=>$product["ProductName"],
                            "UnitsOnOrder"=>$product["UnitsOnOrder"],
                            "Amount"=>$product["Amount"],
                            "Sold"=>$product["Sold"]
                        );
                        $Order["ShipInfo"]= $shipinfo;
                        $Order["PayInfo"]= $payinfo;
                        $params=array(
                            "CustomerID"=>$_SESSION["D-USER"]["CustomerID"],
                            "ShipName"=>$shipinfo["ShipName"],
                            "ShipAddress"=>$payinfo["strShipAddress"],
                            "ProductID"=>$_POST["ProductID"],
                            "Amount"=>$_POST["Amount"],
                            "UnitsOnOrder"=>$product["UnitsOnOrder"],
                            "Monney"=>($product["UnitsOnOrder"]*$_POST["Amount"]+$shipprice),
                            "OrderDetail"=>  json_encode($Order)
                        );
                        //echo "<pre>";print_r($params);echo "</pre>";return;
                        if($this->order_model->insert($params)){
                            $code=1;
                            $msg="Lập đơn hàng thành công";
                            unset($_SESSION["BUY-PROD"]);
                        }else{
                            $code=-1;
                            $msg="Lập đơn hàng thất bại";
                        }
                    }
                }
            }
            
            $rs=array("code"=>$code,"msg"=>$msg);
            echo json_encode($rs);
        }
        function thanhtien(){
            if(!isset($_SESSION["D-USER"])){
                $code=-1;
                $msg="Không xác định được thông tin người mua.";
            }elseif(!isset($_SESSION["BUY-PROD"])){
                $code=-1;
                $msg="Không xác định được thông tin sản phẩm.";
            }else{
                $code=1;
                $msg=number_format($_SESSION["BUY-PROD"]["UnitsOnOrder"]*$_POST["soluong"], 0, ',', '.')."<sup>đ</sup>";
                $_SESSION["TOTALCASH"]=$_SESSION["BUY-PROD"]["UnitsOnOrder"]*$_POST["soluong"];
            }
            $rs=array("code"=>$code,"msg"=>$msg);
            echo json_encode($rs);
        }
          
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */